package com.enjoy.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

/**
 * @author zwf
 * ??????????????????????????????????????http?????????????????????????????????????????url??????client??????request
 * 
 * 
 */
public class HttpPostHandle {
	String url;
	HttpClient client;
	HttpResponse response;
	HttpPost request;
	List<NameValuePair> list;
	
	public HttpPostHandle(String url)
	{
		this.url=url;
		HttpParams parms = new BasicHttpParams();
		
		        parms.setParameter("charset", HTTP.UTF_8);
		
		                HttpConnectionParams.setConnectionTimeout(parms, 8 * 1000);
	
		                HttpConnectionParams.setSoTimeout(parms, 8 * 1000);

		client=new DefaultHttpClient(parms);
		request=new HttpPost(url);
		list=new ArrayList<NameValuePair>();
	}
	
	public void add(String a,String b){
		list.add(new BasicNameValuePair(a,b));
	}
	
	public JSONObject getResponse() 
	{ 
		//String info=null;
		JSONObject a=null;
		try
		{
			Log.i("getting response","");
			request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
			request.setEntity(new UrlEncodedFormEntity(list,HTTP.UTF_8));
			//client.execute(request);
			Header[] hs = request.getAllHeaders();
			for(int i=0;i<hs.length;i++)
			{
				Log.i("huhu",hs[i].getName() + "##" + hs[i].getValue());
			}
			
			response=client.execute(request); 
			Log.i("response status:",response.getStatusLine().getStatusCode()+"");
			String s=EntityUtils.toString(response.getEntity());   //????????????????????json???????????????????????
			Log.i("String s :",s);
		    a=new JSONObject(s);
		    Log.i("a=",a.toString());
			// info=EntityUtils.toString(response.getEntity());
			
		}
		catch(ClientProtocolException e1)
		{
			Log.d("sendRequest",e1.getMessage().toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
			if(response!=null ){
				Log.i("response",response.toString());
			}
			
			
		return a;
	}
	
	
	

}

